package ac.svn.accesscontrol.ui.helper;

import java.util.Set;

import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.SwingUtilities;

import ac.svn.accesscontrol.store.ISVNItem;
import ac.svn.accesscontrol.ui.UIComponentLibrary;

public class IntellFilter
{
	private String criteria = "";
	private Thread thread ;
	private JList targetList;
	private DefaultListModel listModel;
	private Set<ISVNItem> sourceList;
	private JLabel filterResultLabel;
	

	public IntellFilter(String componentId,String model)
	{
		targetList = (JList) UIComponentLibrary.getComponent(componentId);
		listModel = (DefaultListModel) UIComponentLibrary.getComponent(model); 

		thread = new Thread(new Runnable() 
		{
			@Override
			public void run() 
			{
				//Clear list model before filtering.
				listModel.clear();
				
				//Get Items which match the criteria.
				for(ISVNItem item: sourceList)
				{
					if(item.getMetaData().toLowerCase().contains(criteria.toLowerCase()))
					{
						listModel.addElement(item);
						targetList.setSelectedIndex(0);					
					}
				}
				
				//Display Match Result.
				setResultText(String.format(" Matches Found (%d) ", (listModel.size())));

				SwingUtilities.invokeLater(new Runnable() 
				{
					@Override
					public void run() 
					{
						SwingUtilities.updateComponentTreeUI(targetList);						
					}
				});
			}
		}) ;
	}

	public void filterList(Set<ISVNItem> sourceSet, String criteria) {
		this.sourceList = null;
		this.sourceList = sourceSet;
		this.criteria = criteria;
		if(thread.isAlive())
		{
			thread.interrupt();
		}
		thread.run();
	}

	private void setResultText(String message)
	{
		if(null != this.filterResultLabel)
		{
			filterResultLabel.setText(message);
		}
	}

	/**
	 * @param filterResultLabel the filterResultLabel to set
	 */
	public void setFilterResultLabel(JLabel filterResultLabel) {
		this.filterResultLabel = filterResultLabel;
		setResultText("Filter Result");
	}

}
